#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   reset.py
@Time    :   2024-07-31 22:31
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   faith01238@hotmail.com
@Homepage : https://liumou.site
@Desc    :   网卡设置
"""
from os import system
from sys import exit


def text_hosts(ip: str):
	"""
	设置主机文件
	:param ip: 主机IP地址
	:return:
	"""
	txt = f"""127.0.0.1 localhost.localdomain localhost
{ip} pve.example pve

# The following lines are desirable for IPv6 capable hosts

::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
"""
	try:
		with open(f'/etc/hosts', 'w', encoding='utf-8') as f:
			f.write(txt)
	except Exception as e:
		print(e)
		exit(2)
	text = f"""
------------------------------------------------------------------------------

Welcome to the Proxmox Virtual Environment. Please use your web browser to 
configure this server - connect to:

  https://{ip}:8006/

------------------------------------------------------------------------------
"""
	try:
		with open('/etc/issue', 'w', encoding='utf-8') as f:
			f.write(text)
	except Exception as e:
		print(e)
		exit(2)


def text_eth_default():
	return """auto lo
iface lo inet loopback

iface enp1s0 inet manual
iface enx68e43b3084e6 inet manual
iface wlo1 inet manual


auto vmbr0
iface vmbr0 inet static
        address 172.22.11.120/24
        gateway 172.22.11.254
        bridge-ports enp1s0
        bridge-stp off
        bridge-fd 0


auto vmbr1
iface vmbr1 inet manual
        bridge-ports enx68e43b3084e6
        bridge-stp off
        bridge-fd 0
#USB-WAN

auto vmbr2
iface vmbr2 inet manual
        bridge-ports wlo1
        bridge-stp off
        bridge-fd 0
#WIFI
"""


def text_eth_wifi():
	"""
	使用WiFi作为LAN,原生作为WAN
	:return:
	"""
	return """auto lo
	iface lo inet loopback

	iface enp1s0 inet manual
	iface enx68e43b3084e6 inet manual
	iface wlo1 inet manual


	auto vmbr0
	iface vmbr0 inet static
	        address 172.22.10.120/24
	        gateway 172.22.10.254
	        bridge-ports wlo1
	        bridge-stp off
	        bridge-fd 0

	auto vmbr1
	iface vmbr1 inet manual
	        bridge-ports enp1s0
	        bridge-stp off
	        bridge-fd 0
	#WIFI
	"""


def text_eth_usb_lan():
	"""
	使用USB作为LAN,原生作为WAN
	:return:
	"""
	return """auto lo
	iface lo inet loopback

	iface enp1s0 inet manual
	iface enx68e43b3084e6 inet manual
	iface wlo1 inet manual


	auto vmbr0
	iface vmbr0 inet static
	        address 172.22.11.120/24
	        gateway 172.22.11.254
	        bridge-ports enx68e43b3084e6
	        bridge-stp off
	        bridge-fd 0

	auto vmbr1
	iface vmbr1 inet manual
	        bridge-ports enp1s0
	        bridge-stp off
	        bridge-fd 0
	#WIFI
	"""


def text_eth_lan():
	"""
	原生作为LAN
	:return:
	"""
	return """auto lo
	iface lo inet loopback

	iface enp1s0 inet manual


	auto vmbr0
	iface vmbr0 inet static
	        address 172.22.11.120/24
	        gateway 172.22.11.254
	        bridge-ports enp1s0
	        bridge-stp off
	        bridge-fd 0
	"""


class PveEth:
	def __init__(self):
		"""
		初始化网络配置管理类，设置网络接口配置文件路径。
		该方法定义了类中将要使用的各种网络配置文件及其备份文件的路径。
		这些文件路径是用于后续操作如备份、修改等网络设置操作的基础。
		"""
		# 以太网（USB）接口配置文件路径
		self.eth_usb = '/etc/network/interfaces.d/eth_usb'
		# 以太网（USB）接口配置文件备份路径
		self.eth_usb_bak = '/etc/network/interfaces.d/eth_usb.bak'
		# 无线网络接口配置文件路径
		self.eth_wifi = '/etc/network/interfaces.d/wifi'
		# 网络配置主文件路径
		self.eth_config = '/etc/network/interfaces'
		# 初始化并存储以太网默认配置文本对象
		self.text_eth_default = text_eth_default()

	def write(self, text):
		"""
		将指定的文本写入到配置文件中。
		参数:
		- text: 需要写入文件的文本内容。
		该方法会尝试打开并覆盖写入指定的文本到配置文件中。如果在写入过程中发生异常，
		将会打印出具体的异常信息。
		"""
		try:
			# 打开配置文件以写入文本内容，如果文件存在会被覆盖内容。
			with open(self.eth_config, 'w', encoding='utf-8') as f:
				# 将传入的文本写入到文件中。
				f.write(text)
		except Exception as e:
			# 捕获并打印任何在文件写入过程中发生的异常。
			print(e)

	def restart(self):
		"""
		重启网卡
		:return:
		"""
		# 使用system调用systemctl命令重启networking服务
		# 如果返回值为0，表示重启成功
		if system('systemctl restart networking') == 0:
			print('重启网卡成功')
		else:
			print('重启网卡失败')

	def set_boot(self, on, off: str):
		"""
		设置开机启动
		:param on: 需要开机自启的虚拟机ID
		:param off: 不需要启动的虚拟机ID
		:return:
		"""
		cmd = f'qm set {on} --onboot 1'
		if system(cmd) == 0:
			print(f'设置虚拟机{on}开机启动成功')
			system(f'qm start {on}')
		else:
			print(f'设置虚拟机{on}开机启动失败')
		cmd = f'qm set {off} --onboot 0'
		if system(cmd) == 0:
			print(f'设置虚拟机{off}开机启动成功')
			system(f'qm stop {off}')
		else:
			print(f'设置虚拟机{off}开机启动失败')

	def select(self):
		"""
		选择网卡配置
		:return:
		"""
		while True:
			# 显示网卡配置选项
			print('[1] 初始化网卡配置,使用原生网卡作为管理(LAN),USB作为WAN,WIFI作为LAN')
			print('[2] 使用原生作为WAN,WIFI作为LAN')
			print('[3] 使用原生作为WAN,USB作为LAN')
			print('[4] 使用原生作为LAN,其他忽略')
			print('[0] 退出')
			try:
				# 获取用户选择
				choice = int(input('请选择:'))
				if choice == 1:
					# 选择初始化网卡配置
					self.write(text=self.text_eth_default)
					self.set_boot(on='100', off='200')
					text_hosts(ip='172.22.11.120')
					return
				elif choice == 2:
					# 选择原生作为WAN，WIFI作为LAN
					self.write(text=text_eth_wifi())
					self.set_boot(on='200', off='100')
					text_hosts(ip='172.22.10.120')
					return
				elif choice == 3:
					# 选择原生作为WAN，USB作为LAN
					self.write(text=text_eth_usb_lan())
					self.set_boot(on='200', off='100')
					text_hosts(ip='172.22.11.120')
					return
				elif choice == 4:
					# 选择原生作为LAN，其他忽略
					self.write(text=text_eth_lan())
					text_hosts(ip='172.22.11.120')
					return
				elif choice == 0:
					# 退出程序
					exit(0)
				else:
					# 输入无效，提示错误
					print('输入错误')
			except Exception as e:
				# 捕获异常并打印
				print(e)

	def start(self):
		# 打印任务开始的信息
		print('开始设置网卡')
		# 选择合适的网卡设置
		self.select()
		# 重启网卡使设置生效
		self.restart()
		print("执行下面的命令即可重启设备")
		print("reboot")


if __name__ == '__main__':
	PveEth().start()
